#include "../UDP_Client/UDP_Client.h"

void UDP_ClientAPI()
{
  const size_t BufSize=1024;
  char sendBuf[BufSize];
  char recvBuf[BufSize];

  //加载Windows环境
  WORD ver = MAKEWORD(2, 2);
  WSADATA dat;
  WSAStartup(ver, &dat);

  //创建socket
  SOCKET Client_sock = socket(AF_INET, SOCK_DGRAM, 0);
  if (-1 == Client_sock) {
    printf("Build UDP_client's socket failed!!!\n");
  }
  else {
    printf("Build UDP_client's socket successful...\n");
  }
  //
  sockaddr_in Server_sin = {};
  Server_sin.sin_family = AF_INET;
  Server_sin.sin_port = htons(SERVER_PORT);
  //Server_sin.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); //INADDR_ANY为默认IP
  //将十进制SERVER_IP转化为二进制保存至Server_sin.sin_addr中
  inet_pton(AF_INET, SERVER_IP, &Server_sin.sin_addr);
  sockaddr_in Server_sock;
  socklen_t len=sizeof(Server_sock);

  //缓冲区
  while (true) {
    //输入发送信息
    printf("Please input:\n");
    scanf_s("%s", sendBuf, BufSize);
    sendBuf[strlen(sendBuf)] = '\0';

    //调用sendto函数，将缓冲区内的数据发送至服务端
    sendto(Client_sock, sendBuf, strlen(sendBuf), 0, (SOCKADDR*)&Server_sin, sizeof(SOCKADDR));

    int nlen = recvfrom(Client_sock, recvBuf, sizeof(recvBuf), 0, (SOCKADDR*)&Server_sock, &len);
    printf("%d", nlen);

    if (nlen > 0)
    {
      recvBuf[nlen] = '\0';      //给字符数组加一个'\0'，表示结束了。不然输出有乱码
      if (strcmp(recvBuf, "bye") == 0)
      {
        printf("Server close!!!");//当服务器发来bye时，关闭socket
        closesocket(Client_sock);
        break;
      }
      else
      {
        printf("Recv message sucessful... Message:%s\n", recvBuf);
      }
    }
    memset(sendBuf, 0, sizeof(sendBuf));
    memset(recvBuf, 0, sizeof(recvBuf));
  }
  //关闭客户端连接
  closesocket(Client_sock);
  //
  WSACleanup();
  printf("Client closed...");
  getchar();
}